//
//  JRrootTabBar.swift
//  myWeibo
//
//  Created by 樊健荣 on 16/7/18.
//  Copyright © 2016年 樊健荣. All rights reserved.
//

import UIKit

class JRrootTabBar: UITabBar {

    //按钮点击跳转闭包
    
    var composeCallBack: (() -> Void)?
    
    
    ///懒加载按钮
    lazy var composeBtn: UIButton = {
        let btn = UIButton(type: UIButtonType.Custom)
        
        //设置按钮图片
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Selected)
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Selected)
        
        //添加点击事件
        btn.addTarget(self, action: "centerBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        //将按钮添加到tabbar
        self.addSubview(btn)
        
        
        return btn
    }()
    
    let btnCount = 5
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let width = self.frame.width / CGFloat(btnCount)
        
        var index = 0
        //遍历tabBar中的子控件,重新布局留出中间空位
        for item in self.subviews {
            //判断subView类型为UITabBarButton时候,才重新布局frame
            if item.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                item.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: self.frame.height)
                
                
                index++
                if index == 2 {
                    index++
                }
            }
        }
        composeBtn.frame = CGRect(x: 2 * width, y: 0, width: width, height: self.frame.height)
    }
    
    //按钮点击事件
    func centerBtnClick () -> Void {
        print("按钮点击事件")
        composeCallBack?()
    }
    
    

}
